<?php

namespace App\Http\Controllers\Admin\V1;

use App\Exports\LoginExport;
use App\Http\Controllers\Controller;
use App\Models\LoginLog;
use App\Models\User;
use App\Transformers\Admin\LoginLogTransformer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Maatwebsite\Excel\Facades\Excel;

class LoginLogController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @return Response
     */
    public function index()
    {

        $userId = [];
        if (request()->has('username')) {
            $userId = User::where('username', 'like', '%' . request()->input('username') . '%')->pluck('id');
        }

        $loginLogs = LoginLog::pimp()
            ->when(request()->has('username'), function ($query) use ($userId) {
                $query->whereIn('user_id', $userId);
            })
            ->when((request()->has('startTime') && request()->has('endTime')), function ($query) {
                $query->whereBetween('created_at', [request()->input('startTime'), request()->input('endTime')]);
            })
            ->paginate($this->pageLimit());

        return $this->response->paginator($loginLogs, new LoginLogTransformer());
    }

    /**
     * 日志导出
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function export(Request $request)
    {
        return Excel::download(new LoginExport($request), '登录日志-' . Carbon::today() . '.xlsx',\Maatwebsite\Excel\Excel::XLSX);
    }

    /**
     * 统计
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|int
     */
    public function count()
    {
        return LoginLog::query()
            ->selectRaw("str_to_date(created_at,'%Y-%m-%d') AS time, COUNT(created_at) AS num")
            ->groupBy('time')
            ->get();
    }
}
